'''
Created on 31. 1. 2014

@author: pb
'''

import os
import sys
import atexit
import data
import logging
from datetime import datetime
import env
import time

from apscheduler.scheduler import Scheduler

log = logging.getLogger(__name__)

    
    
class Job:
    
    def run(self):
        pass
       

class DetectorJob(Job):
    
    def __init__(self, hwid=None, place=None):
        self.hwid = hwid
        self.place = place
        
    def run(self):
        log.debug("DetectorJob.run")
        for d in data.Data().detectors(hwid=self.hwid, place=self.place):
            d.measure();
        pass
    
    
class AgregateJob(Job):
    
    interval = 1

    def run(self):
        log.debug("AgregateJob.run")
        
        ms = {}
        e = (datetime.now() - datetime.timedelta(minutes=self.interval))
        
        with env.Db() as db:
            c = db.get_connection().cursor()
            c.execute("create temp table t-aggr as select * from measuring where ctime <= :e", {'e': e})
            
            
             
            for i in c.execute("select * from t-aggr").fetchall():
                m = data.Measuring(i['hwid'], i['dtype'], i['place'])
                m.ctime = time.gmtime(i['ctime'])
                m.value = i['value']
                 
       
          
        
        
    
class EchoJob(Job):
    pass  
  
   
if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    
    sched = Scheduler(standalone=True)
    
    
    sched.add_interval_job(DetectorJob().run, seconds=4)
    sched.start()
    
    
    atexit.register(lambda: sched.shutdown(wait=False))
    
    